﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

[ImageEffectAllowedInSceneView, RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode]
public class AlchemyAO : MonoBehaviour {

	[SerializeField]
	Material m_alchemyAO;

	[SerializeField]
	Material m_blur;

	[SerializeField]
	Material m_blend;

	private void Start () {
		var cam = GetComponent<Camera>();
		cam.depthTextureMode = DepthTextureMode.DepthNormals;
	}

	private void OnRenderImage(RenderTexture source, RenderTexture destination) {
		// save color buffer
		Graphics.Blit(source, destination);
		var MapColor = RenderTexture.GetTemporary(source.descriptor);
		MapColor.filterMode = FilterMode.Point;
		var MapAO = RenderTexture.GetTemporary(source.descriptor);
		MapAO.filterMode = FilterMode.Bilinear;
		Graphics.Blit(source, MapColor);
		Graphics.SetRenderTarget(source);
		GL.Clear(false, true, Color.black);
		// Alchemy AO
		Graphics.Blit(MapColor, source, m_alchemyAO);
		Graphics.Blit(source, MapAO);
		// Blur
		Graphics.Blit(MapAO, source, m_blur);
		Graphics.Blit(source, MapAO);
		// Blend
		Graphics.Blit(MapColor, source);
		m_blend.SetTexture(nameof(MapAO), MapAO);
		Graphics.Blit(MapColor, source, m_blend);
		Graphics.Blit(source, destination);
		// Release temp RT
		RenderTexture.ReleaseTemporary(MapColor);
		RenderTexture.ReleaseTemporary(MapAO);
	}
}